import os
from openpyxl import Workbook
from datetime import datetime
from .write_csv import write_csv

class output_control(object):
    def __init__(self):
        self.__output_path = "."
        self.__verbose = False
        self.__method = ""
        #self.__outputinfo = []
        #self.__output_temp = []
        #self.__headinfo = []
        self.__loginfo = []
        self.__multi_job = False
        self.__i_job = 0

        self._csv_files = {}

    def initial(self, yaml_config, method: str):
        self.__start_time = datetime.now()
        self.__method = method
        self.__output_path = yaml_config.get("OutputPath", ".")
        self.__output_path = f"{self.__output_path}/Job_{self.__start_time.strftime('%Y%m%d_%H%M%S')}_{self.__method}"
        self.__verbose = yaml_config.get("Verbose", False)
        self.__output_name = self.__method + f"_result"
        #self.__output_name = self.__method + f"_{now.strftime('%Y%m%d_%H%M%S')}.csv"
        if not os.path.exists(self.__output_path):
            os.mkdir(self.__output_path)
            
        self.__log_file =  open(f"{self.__output_path}/{self.__output_name}.log", 'w')
        self.write_log(f"Operations start at {self.__start_time.strftime('%b. %d, %Y -- %H:%M:%S')}.")

    def create_csv_file(self, name):
        self._csv_files[name] = write_csv(f"{self.__output_path}/{name}.csv")
        return self._csv_files[name]

    @property
    def csv_file(self):
        return self._csv_files

    '''
    def multi_job(self):
        self.__multi_job = True
        now = datetime.now()
        self.__output_path = f"{self.__output_path}/Job_{now.strftime('%Y%m%d_%H%M%S')}_{self.__method}"
        if not os.path.exists(self.__output_path):
            os.makedirs(self.__output_path)

    def write_head(self, data):
        if isinstance(data, list):
            self.__headinfo = self.__headinfo + data
        elif isinstance(data, (int, float, str, bool)):
            self.__headinfo.append(data)
        else:
            raise TypeError("Only list/int/float/str/bool are support.")
    '''
    def write_log(self, data, print_out=True):
        if isinstance(data, list):
            for iline in data:
                if print_out:
                    print(iline)
                self.__log_file.write(iline)
        if isinstance(data, (str)):
            if print_out:
                print(data)
            self.__log_file.write(data+'\n')
        else:
            raise TypeError("Only list/str are support.")

    '''
    def write_line(self, data, end = False):
        if isinstance(data, list):
            self.__output_temp = self.__output_temp + data
        elif isinstance(data, (int, float, str, bool)):
            self.__output_temp.append(data)
        else:
            raise TypeError("Only list/int/float/str/bool are support.")
        
        if end == True:
            if self.__output_temp[0] == -1:
                if self.__verbose == False:
                    self.__output_temp = []
                return
            self.__outputinfo.append(self.__output_temp)
            self.__output_temp = []
    @staticmethod
    def format_a_line(a_list: list):
        if len(a_list) == 0:
            return ""
        a_line = f"{a_list[0]}"
        for astr in a_list[1:]:
            a_line = a_line + f",{astr}"
        a_line = f"{a_line}\n"
        #print(a_line)
        return a_line

    '''
    @property
    def i_job(self):
        return self.__i_job

    def new_job(self):
        self.__i_job = self.__i_job + 1

    @property
    def output_path(self):
        return self.__output_path

    @property
    def output_name(self):
        return self.__output_name

    def multi_log(self):
        return self.__multi_job
        
    def save_log(self):
        end_time = datetime.now()
        self.write_log(f"\nOperations end at {end_time.strftime('%b. %d, %Y -- %H:%M:%S')}.")
        mission_time = (end_time - self.__start_time).seconds
        self.write_log(f"Total time cost: {mission_time//3600}:{mission_time//60}:{mission_time%60}.")
        self.__log_file.close()

global_output = output_control()